<template>
    <el-card shadow="always" >
        <!-- <h2 class="title">{{route.query.id}}</h2> -->
        <!-- <h2 class="title">{{route.params.id}}</h2> -->
        <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入菜单或者权限名称"
        v-model="value"
        :data="data"
        :titles="['所有菜单/权限', '已选择的菜单/权限']"
       
        >
        </el-transfer>
        <div class="flex justify-end" v-if="route.query.id">
            <el-button type="primary"  style="margin-top: 20px;" @click="submitUpdateUserAuth">保存</el-button>
        </div>
        <!-- <div class="selected-menus">
        <h3 class="subtitle">已选择的菜单/权限：</h3>
        <ul class="menu-list">
            <li v-for="menu in selectedMenus" :key="menu.key" class="menu-item">{{ menu.label }}</li>
        </ul>
        </div> -->
    </el-card>
</template>
<script setup>
import { ref,reactive,watch } from 'vue'
import { getAllAuth,updateUserAuth,getUserAuth } from "@/api/manager.js"
import { ElTransfer } from 'element-plus'
import { useUserStore } from '@/stores/user.js'
import { useRoute } from 'vue-router'
const route = useRoute()
const userStore = useUserStore()

// 获取所有权限
const data = ref([])
const getAllAuthData = async () => {
    const res = await getAllAuth()
    res.allAuth.forEach((item, index) => {
          data.value.push({
            label: item.name,
            key: index,
            id: item.id,
            
          })
        })
}
getAllAuthData()
// 回显权限
const value = ref([]) // 右侧的值

const getUserAuthData =  async() => {
    const res = await getUserAuth(route.query.id)
    console.log('res',res.auths)
   if(res.auths){
        const authIds2 = JSON.parse(res.auths) 
        data.value.forEach((item, index) => {
            // console.log('33',item.id)
        if (authIds2.includes(item.id)) {
            // console.log('44',index)
            value.value.push(index)
        }
    })
    }else{
        value.value = []
    }
    
    
}

watch(() => route.query.id, (newValue) => {  
    // console.log("watch old",route.query.id)
    // console.log("watch new", newValue)
    getUserAuthData()
} 
,
{ immediate: true });

const filterMethod = (query, item) => {
      return item.label.toLowerCase().includes(query.toLowerCase());
    };

const selectedMenus = ref([])




watch(value, (newValue) => {
    selectedMenus.value = data.value.filter(menu => newValue.includes(menu.key));
}, { immediate: true });

const selecteId= ref([]);
const submitUpdateUserAuth = async () => {
    selectedMenus.value.forEach((item, index) => {
        selecteId.value.push(item.id)
})
    const res = await updateUserAuth({authIds:selecteId.value,uid:route.query.id})
    // console.log(selecteId.value)
}




</script>
<style scoped>
:deep(.el-transfer-panel){
width: 470px!important; /* 穿梭框宽度 */

}
:deep(.el-transfer-panel__body) {
height: 450px!important; /* 穿梭框列表高度 */
}

</style>